#include <stdio.h>
#include <sqlite3.h>
#include <time.h>
#include <string.h>
#include <unistd.h>

#include "get_temp.h"
#include "get_ID.h"

int sqlite_insert(sqlite3 **db)
{
	int                     rv = -1;
	time_t                  rawtime;
	struct                  tm *info;
	char                    *errmsg = NULL;
	char                    sql[1024] = {};

	struct rpi_ID_s         rpi_ID = {};
	struct rpi_data_s       rpi_data = {};

	rv = get_temperature(&rpi_data);
	if(rv<0)
	{
		printf("get time failure,return value:%d\n",rv);
		return -1;
	}

	time( &rawtime );
	info = localtime( &rawtime );

	rv =  get_ID(&rpi_ID);
		if(rv<0)
		{
			printf("get ID failure,return value:%d\n",rv);
			return -2;
		}

	memset(sql, 0, sizeof(sql));
	sprintf(sql,"insert into temp values('%s','%s','%f')",rpi_ID.ID, asctime(info), rpi_data.temp);

	rv = sqlite3_exec(*db, sql, NULL, NULL, &errmsg);
	if(rv != SQLITE_OK)
	{
		printf("error:%s\n", errmsg);
		return -3;
	}
	printf("insert ok");
	sleep(3);

	return 0;
}
